import React, { useState } from 'react'
import { useTodoDispatch, useTodoSelector } from '@/stores'
import { addTodo, TodoItem, fetchTodos } from '@/stores/todoSlice'

type TodoListProps = {
  onItemClick: (item: TodoItem) => void
}

const TodoList: React.FC<TodoListProps> = ({ onItemClick }) => {
  const [inputValue, setInputValue] = useState('')

  const todos = useTodoSelector((state) => state.todo)

  const dispatch = useTodoDispatch()

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setInputValue(e.target.value)
  }

  const handleAddTodo = () => {
    if (inputValue.trim()) {
      dispatch(addTodo(inputValue))
      setInputValue('')
    }
  }

  React.useEffect(() => {
    dispatch(fetchTodos()) 
  }, [dispatch])

  return (
    <div className="container mx-auto p-20 text-white">
      <div className="flex justify-center">
        <input
          type="text"
          value={inputValue}
          onChange={handleInputChange}
          className="border border-gray-300 rounded p-2 mr-2 bg-black text-white"
          placeholder="添加一条任务"
        />
        <button onClick={handleAddTodo} className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
          添加
        </button>
      </div>
      <div className="max-w-md mx-auto mt-10">
        <div className="bg-black shadow-md rounded-lg p-5">
          <h2 className="text-lg font-semibold text-white border-b pb-2">任务列表</h2>
          <ul className="list-disc pl-5 mt-3">
            {todos.map((item) => (
              <div key={item.id} className="flex justify-between mb-2">
                <li className="text-white mt-2">
                  {item.content}
                </li>
                <button onClick={() => onItemClick(item)} className="bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded">
                  详情
                </button>
              </div>
            ))}
          </ul>
        </div>
      </div>
    </div>
  )
}

export default TodoList
